<template>
  <div class="app-container">
    <el-form :show-message="!($route.query.isInfo || isInfo)" ref="elForm" :disabled="$route.query.isInfo || isInfo"
      :model="formData" :rules="rules" size="medium" label-width="130px">
      <h2 style="text-align: center">购置化学药品审批</h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="检测部门" prop="deptId">
            <el-cascader :props="{ value: 'id', checkStrictly: true }" :show-all-levels="false" ref="reference"
              placeholder="请选择检测部门" :style="{ width: '100%' }" v-model="formData.deptId" :options="deptOptions"
              @change="changeCascader"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="供应品名称" prop="chemistryGoodsDirectoryId">
            <el-select filterable v-model="formData.chemistryGoodsDirectoryId" placeholder="请选择供应品名称" clearable
              @change="changeMl" :style="{ width: '100%' }">
              <el-option v-for="(item, index) in muSelectList" :key="index" :label="item.name"
                :value="item.chemistryGoodsDirectoryId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="供应商" prop="supplierId">
            <el-select filterable v-model="formData.supplierId" placeholder="请选择供应商" clearable @change="changeSupp"
              :style="{ width: '100%' }">
              <el-option v-for="(item, index) in supplierIdOptions" :key="index" :label="item.supplierName"
                :value="item.supplierBaseId" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="主要用途" prop="useInfo">
            <el-input disabled v-model="formData.useInfo" placeholder="请输入主要用途" clearable
              :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="技术要求" prop="techInfo">
            <el-input v-model="formData.techInfo" placeholder="请输入技术要求" clearable :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="数量" prop="num">
            <el-input-number v-model="formData.num" placeholder="数量" :step="1" :style="{ width: '100%' }"
              controls-position="right"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单价" prop="price">
            <el-input-number v-model="formData.price" placeholder="单价" :step="1" :style="{ width: '100%' }"
              controls-position="right"></el-input-number>
          </el-form-item>
        </el-col>


        <el-col :span="8">
          <el-form-item label="申请人" prop="create_by">
            <el-input disabled v-model="formData.create_by" placeholder="请输申请人" clearable
              :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="技术指标" prop="tecTarget">
            <el-input
              disabled
              v-model="formData.tecTarget"
              placeholder="请输入技术指标"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>-->
        <el-col :span="8">
          <el-form-item label="单位" prop="unitValue">
            <el-select v-model="formData.unitValue" placeholder="请选择单位" clearable @change="changeUnit"
              :style="{ width: '100%' }">
              <el-option v-for="(item, index) in dict.type.goods_unit_type" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备案情况" prop="isRecord">
            <el-select v-model="formData.isRecord" placeholder="请选择备案情况" clearable @change="changeUnit"
              :style="{ width: '100%' }">
              <el-option label="有" :value="0" ></el-option>
              <el-option label="无" :value="1" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供货情况" prop="isGoods">
            <el-select v-model="formData.isGoods" placeholder="请选择供货情况" clearable @change="changeUnit"
              :style="{ width: '100%' }">
              <el-option label="有" :value="0" ></el-option>
              <el-option label="无" :value="1" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <h4 class="form-header h4" v-if="formData.supplierId">供应商信息</h4>
      <el-row :gutter="15" v-if="formData.supplierId">
        <el-col :span="8">
          <el-form-item label="供应商名称">{{ formData.supplierName || "--" }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人">{{ formData.person || "--" }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="地址">{{ formData.address || "--" }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话">{{ formData.phone || "--" }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机">{{ formData.mobilePhone || "--" }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮编">{{ formData.zipCode || "--" }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="传真">{{ formData.fax || "--" }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商类型">
            <dict-tag :options="dict.type.sys_supplier_type" :value="formData.supplierType" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供方响应情况">{{ formData.response || "--" }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质保书">
            <ImagePreview v-for="item in formData.qualityUrl
              ? formData.qualityUrl.split(',')
              : []" width="150px" height="150px" :src="item"></ImagePreview>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="资质证书">
            <ImagePreview v-for="item in formData.qualificationsUrl
              ? formData.qualificationsUrl.split(',')
              : []" width="150px" height="150px" :src="item"></ImagePreview>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品说明书" prop="isInstruction">
            <el-radio-group v-model="formData.isInstruction" size="medium">
              <el-radio v-for="(item, index) in isInstructionOptions" :key="index" :label="item.value.toString()"
                :disabled="item.disabled">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品质量证明" prop="isMass">
            <el-radio-group v-model="formData.isMass" size="medium">
              <el-radio v-for="(item, index) in isMassOptions" :key="index" :label="item.value.toString()"
                :disabled="item.disabled">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8" v-if="formData.isBusLicense == 0">
          <el-form-item label="营业执照">
            <ImagePreview width="100px" height="100px" :src="formData.busLicenseUrl"></ImagePreview>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="(!$route.query.isInfo &&
        !isInfo &&
        formData.supplierId &&
        formData.otherFileUrl) ||
        (($route.query.isInfo || isInfo) && formData.otherFileUrl)
        ">
        <el-col :span="8">
          <el-form-item label="附件信息">
            <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear"
              tag="ul">
              <li :key="file" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in oss">
                <el-link :href="`${file.url}`" :underline="false" target="_blank">
                  <span class="el-icon-document">{{ file.fileName }}</span>
                </el-link>
              </li>
            </transition-group>
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="formData.supplierId">
        <h4 class="form-header h4" v-if="(!$route.query.isInfo && !isInfo && formData.isInstruction == 0) ||
          (($route.query.isInfo || isInfo) && formData.instructionUrl)
          ">产品说明书</h4>
        <el-form-item label prop="instructionUrl" v-if="(!$route.query.isInfo && !isInfo && formData.isInstruction == 0) ||
          (($route.query.isInfo || isInfo) && formData.instructionUrl)
          ">
          <FileUpload :isDelete="!$route.query.isInfo" v-model="formData.instructionUrl"></FileUpload>
        </el-form-item>
        <h4 class="form-header h4" v-if="(!$route.query.isInfo && !isInfo && formData.isMass == 0) ||
          (($route.query.isInfo || isInfo) && formData.massUrl)
          ">产品质量证明文件</h4>
        <el-form-item label prop="massUrl" v-if="(!$route.query.isInfo && !isInfo && formData.isMass == 0) ||
          (($route.query.isInfo || isInfo) && formData.massUrl)
          ">
          <FileUpload :isDelete="!$route.query.isInfo" v-model="formData.massUrl"></FileUpload>
        </el-form-item>
      </template>

      <el-col :span="24" v-if="btnShow">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm(1)">提交</el-button>
          <el-button v-if="!($route.query.isInfo || isInfo) && formData.status != 'end'" type="primary"
            @click="submitForm(0)">暂存</el-button>

          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import {
  consume_buyAdd,
  updategconsume_buy,
  consume_buyInfo
} from "@/api/quality/goods/consumeBuy.js";
import { getuser } from "@/api/finance/bxgl/index.js";
import { deptTreeSelect } from "@/api/system/user.js";
import { selectList } from "@/api/supplier/SupplierBase.js";
import { selectList as muSelect } from "@/api/quality/goods/directory.js";

import store from "@/store";
console.log();
export default {
  dicts: ["sys_supplier_type", 'goods_unit_type'],

  components: {},
  props: {
    isInfo: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ""
    },
    btnShow: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      carSelectList: [],
      formData: {
        chemistryGoodsDirectoryId: undefined,
        num: 1,
        price: undefined,
        useInfo: undefined,
        techInfo: undefined,
        supplierId: undefined,
        deptId: undefined,
        create_by: store.state.user.nickName,
        instructionUrl: undefined,
        massUrl: undefined,
        isInstruction: "0",
        isMass: "0",
        tecTarget: undefined
      },
      isInstructionOptions: [
        {
          label: "有",
          value: 0
        },
        {
          label: "无",
          value: 1
        }
      ],
      isMassOptions: [
        {
          label: "有",
          value: 0
        },
        {
          label: "无",
          value: 1
        }
      ],
      oss: [],
      rules: {
        tecTarget: [
          {
            required: true,
            message: "请上输入技术指标",
            trigger: "blue"
          }
        ],
        instructionUrl: [
          {
            required: false,
            message: "请上传产品说明书",
            trigger: "change"
          }
        ],
        massUrl: [
          {
            required: false,
            message: "请上传质量文件申请",
            trigger: "change"
          }
        ],
        chemistryGoodsDirectoryId: [
          {
            required: true,
            message: "请输入供应品名称",
            trigger: "blur"
          }
        ],
        num: [
          {
            required: true,
            message: "供应品数量",
            trigger: "blur"
          }
        ],
        price: [
          {
            required: true,
            message: "单价",
            trigger: "blur"
          }
        ],
        // useInfo: [
        //   {
        //     required: true,
        //     message: "请输入主要用途",
        //     trigger: "blur"
        //   }
        // ],
        techInfo: [
          {
            required: true,
            message: "请输入技术要求",
            trigger: "blur"
          }
        ],
        supplierId: [
          {
            required: true,
            message: "请选择供应商",
            trigger: "change"
          }
        ],
        deptId: [
          {
            required: true,
            message: "请选择检测部门",
            trigger: "change"
          }
        ]
      },
      supplierIdOptions: [],
      deptOptions: [],
      muSelectList: []
    };
  },
  computed: {},
  created() {
    console.log(store.state.user);
    this.selectList();
    this.muSelect();
    this.getDeptTree();
    // this.getUser();
    if (this.$route.query.isEdit || this.$route.query.isInfo || this.isInfo) {
      this.getinfo();
    }
  },
  mounted() { },
  methods: {
    getUser() {
      getuser(store.state.user.id).then(response => {
        if (
          this.$route.query.isEdit ||
          this.$route.query.isInfo ||
          this.isInfo
        ) {
        } else {
          this.formData.dept = response.data.user.dept.deptName;

          this.formData.deptId = response.data.user.dept.deptId;
        }
        console.log(this.formData.deptId);
      });
    },
    changeMl(i) {
      let row = this.muSelectList.find(e => e.chemistryGoodsDirectoryId == i);
      if (row) {
        this.formData.goodsName = row.name;
        this.formData.spec = row.spec;
        this.formData.useInfo = row.useInfo;
        this.formData.tecTarget = row.tecTarget;

        this.formData.techInfo = row.techInfo;
      } else {
        this.formData.goodsName = undefined;
        this.formData.spec = undefined;
        this.formData.useInfo = undefined;
        this.formData.tecTarget = undefined;

        this.formData.techInfo = undefined;
      }
    },
    changeCascader(e) {
      console.log(e);
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        console.log(this.deptOptions);
        if (!this.$route.query.isEdit && !this.$route.query.isInfo && !this.isInfo) {
          this.formData.deptId = store.state.user.dept.deptId;
        }
      });
    },
    muSelect() {
      muSelect({ effectStatus: 1, chemicals: 1 }).then(response => {
        this.muSelectList = response.data;
      });
    },
    /** 查询供应商下拉树结构 */
    selectList() {
      selectList().then(response => {
        this.supplierIdOptions = response.data;
      });
    },

    getinfo() {
      return consume_buyInfo(this.$route.query.id || this.id).then(response => {
        this.formData = response.data;
        this.formData.create_by = response.data.createByName;
        this.formData.qualificationsUrl =
          response.data.supplier.qualificationsUrl;
        this.formData.qualityUrl = response.data.supplier.qualityUrl;
        this.formData.response = response.data.supplier.response;
        this.formData.fax = response.data.supplier.fax;
        this.formData.zipCode = response.data.supplier.zipCode;
        this.formData.supplierType = response.data.supplier.supplierType;
        this.formData.mobilePhone = response.data.supplier.mobilePhone;

        this.oss = this.formData.otherFileName.split(",").map((e, i) => {
          return {
            fileName: e,
            url: this.formData.otherFileUrl.split(",")[i]
          };
        });
      });
    },
    handleAdd() {
      this.details.push({ name: "", url: "" });
    },
    handleDele() {
      if (this.details.length == 1) return;
      this.details.pop();
    },
    changeSupp() {
      let row = this.supplierIdOptions.find(
        i => i.supplierBaseId === this.formData.supplierId
      );
      console.log(row);
      this.oss = row.oss;
      this.formData = { ...this.formData, ...row };
      this.formData.instructionUrl = undefined;
      this.formData.massUrl = undefined;
    },
    submitForm(e) {
      let query = JSON.parse(JSON.stringify(this.formData));
      if (query.status != 'end') {
        query.status = e == 0 ? 'draft' : 'audit'
      }
      if (query.deptId) {
        query.deptId = this.$refs.reference.getCheckedNodes()[0].value;
        query.dept = this.$refs.reference.getCheckedNodes()[0].label;
      }

      if (e == 0) {
        if (!this.formData.chemistryGoodsDirectoryId) {
          this.$message.warning("请先选择供应品名称");
          return;
        }
        if (this.formData.consumeBuyId != undefined) {
          updategconsume_buy(query).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.resetForm();
          });
        } else {
          consume_buyAdd(query).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.resetForm();
          });
        }
        return
      }
      this.$refs["elForm"].validate(valid => {
        if (valid) {
          let row = this.supplierIdOptions.find(
            i => i.supplierBaseId === this.formData.supplierId
          );
          // query.otherFileName = this.oss.map((e) => e.fileName).join(",");
          // query.otherFileUrl = this.oss.map((e) => e.url).join(",");
          if (query.unitValue && this.dict.type.goods_unit_type.length != 0) {
            query.unitLabel = this.dict.type.goods_unit_type.find(
              i => i.value === query.unitValue
            ).label;
            console.log(query.unitLabel);
          }
          query = { ...query, ...row };

          if (this.formData.consumeBuyId != undefined) {
            updategconsume_buy(query).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            consume_buyAdd(query).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      this.$tab.closeOpenPage();
    }
  }
};
</script>
<style scoped>
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
